package com.qqtech.qquan.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.sys.enums.SysFunctionStatusDictEnum;
import com.qqtech.qquan.sys.enums.SysRoleStatusDictEnum;
import com.qqtech.qquan.sys.model.SysFunctionVo;
import com.qqtech.qquan.sys.model.SysRole;
import com.qqtech.qquan.sys.model.SysRoleQuery;
import com.qqtech.qquan.sys.model.SysRoleVo;
import com.qqtech.qquan.sys.service.SysFunctionService;
import com.qqtech.qquan.sys.service.SysRoleService;
import com.qqtech.qquan.user.model.UserAdmin;

@Controller
@RequestMapping(value = "/sys/role")
public class SysRoleController extends BaseAgentController {
	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private SysFunctionService sysFunctionService;
    
	@Override
	protected BaseService<SysRole> getBaseService() {
		return sysRoleService;
	}
	
	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/role/role-list";
	}

	/**
	 * 列表
	 * @param sysRoleQuery
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(SysRoleQuery sysRoleQuery, HttpServletRequest request,
			HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		Pageable pageKit = new PageKit(sysRoleQuery.getPage(), new PageOrder(Direction.ASC, "id"));
		Page<SysRole> page = sysRoleService.queryPageList(sysRoleQuery, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(page.getNumberOfElements());
		return adminPage;

	}
	
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@RequestParam(required = false) String parentId, HttpServletRequest request,
			HttpServletResponse response) {
		return "/role/role-update";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(SysRole role,HttpServletRequest request, HttpServletResponse response) {
		UserAdmin userAdmin = super.getLoginUser(request, response);
		Result ret = new Result();
		if (StringUtil.isBlank(role.getName())) {
			ret.addErr("请输入角色名称");
		} else {
			SysRoleVo tmpRole = sysRoleService.getByName(role.getName());
			if (tmpRole != null) {
				ret.addErr("此名称已被使用");
			}
		}
		if (ret.checkForm()) {
			role.setUserId(userAdmin.getId());
			role.setStatus(SysRoleStatusDictEnum.ENABLE.getCode()); //1-启用
			sysRoleService.insert(role);
		}
		return ret;
	}

	@RequestMapping(value = "/update/{roleId}", method = RequestMethod.GET)
	public String update(@PathVariable Integer roleId, HttpServletRequest request, HttpServletResponse response) {
		SysRole role = sysRoleService.getById(roleId);
		request.setAttribute("role", role);
		return "/role/role-update";
	}

	@RequestMapping(value = "/update/{roleId}", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(@PathVariable Integer roleId, SysRoleVo param) {
		SysRoleVo role = sysRoleService.getById(roleId);
		Result ret = new Result();
		if (role == null) {
			ret.addErr("角色不存在");
		}
		if (ret.checkForm()) {
			role.setName(param.getName());
			role.setRemark(param.getRemark());
			role.setStatus(param.getStatus());
			role.setFunctionIds(param.getFunctionIds()); // 选中的功能
			role.setUncheckdFunctionId(param.getUncheckdFunctionId()); // 未选中的功能
			sysRoleService.handleUpdateRole(role);
		}
		return ret;
	}
	
	/**
	 * 为角色分配功能时,返回功能的树形组件的json对象
	 */
    @RequestMapping(value="/functree",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
	public void funcTree( HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id"); //父级功能id
		Integer parentId = null;
		if (!StringUtils.isBlank(id)) {
			parentId = Integer.valueOf(id);
		}
		List<SysFunctionVo> functions = sysFunctionService.queryChildrenList(parentId, SysFunctionStatusDictEnum.ENABLE.getCode()); //1：启用
		List<Map<Object, Object>> tree = new ArrayList<Map<Object, Object>>(functions.size());
		String roleId = request.getParameter("roleId");
    	List<SysFunctionVo> selectedMenus =  new ArrayList<SysFunctionVo>();
    	if(!StringUtils.isBlank(roleId)) {
    		//查询获取角色在某一父级菜单下拥有的子菜单功能
    		selectedMenus = sysFunctionService.queryChildrenForRoleList(roleId, parentId, null);
    	}
    	for(SysFunctionVo f : functions) {
    		Map<Object, Object> node = new HashMap<Object, Object>();
			node.put("id", f.getId());
			node.put("text", f.getName());
			if (f.getType() == 1) {
				node.put("state", "closed");
				node.put("iconCls", "icon-folder");
			} else {
				node.put("state", "open");
				node.put("iconCls", "icon-star");
			}
			//node.put("checked", selectedMenus.contains(f));
			if(selectedMenus != null && selectedMenus.size() > 0){
				for(SysFunctionVo selectMenus : selectedMenus){
					if(selectMenus.getId().equals(f.getId())){
						node.put("checked", true);
					}
				}
			}
			
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("parentId", f.getParentId());
			attributes.put("type", f.getType());
			node.put("attributes", attributes);
			tree.add(node);
    	}
    	String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    /**
     * 更新角色与菜单的关系
     * @return
     */
	@RequestMapping(value = "/refresh", method = RequestMethod.POST)
	@ResponseBody
	public Result refresh() {
		Result ret = new Result();
		sysRoleService.updateRoleAndMenu();
		return ret;
	}
}
